<template>
  <view class="timing-container">
    <div class="input-section">
      <label for="project-id">项目 ID:</label>
      <input id="project-id" v-model="projectId" placeholder="请输入项目 ID" />
    </div>
    <div class="display-section">
      <p>计时时长: {{ elapsedTime }} 秒</p>
    </div>
    <div class="button-section">
      <button :disabled="isRunning" @click="startTimer">开始</button>
      <button :disabled="!isRunning" @click="stopTimer">结束</button>
    </div>
  </view>
</template>

<script>
import { saveTiming } from '@/api/timing.js';

export default {
  data() {
    return {
      projectId: '',
      elapsedTime: 0,
      isRunning: false,
      timer: null
    };
  },
  methods: {
    startTimer() {
      this.elapsedTime = 0;
      this.isRunning = true;
      this.timer = setInterval(() => {
        this.elapsedTime++;
      }, 1000);
    },
    async  stopTimer() {
      clearInterval(this.timer);
      this.isRunning = false;
	  try {
	    const data = {
	      projectId: this.projectId,
	      totalTime: this.elapsedTime
	    };
	    const response = await saveTiming(data);
	    console.log('计时时长保存成功', response);
	  } catch (error) {
	    console.error('计时时长保存失败', error);
	  }
      // 重置 projectId 和 elapsedTime
      this.projectId = '';
      this.elapsedTime = 0;
    },
  }
};
</script>

<style scoped>
.timing-container {
  width: 100%;
  padding: 20px;
  margin: 0 auto;
  border: 1px solid #ccc;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.input-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.input-section label {
  margin-right: 10px;
  font-weight: bold;
}

.input-section input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.display-section {
  margin-bottom: 20px;
}

.display-section p {
  font-size: 18px;
  font-weight: bold;
}

.button-section {
  display: flex;
  justify-content: space-between;
}

.button-section button {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.button-section button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.button-section button:nth-child(1) {
  background-color: #28a745;
  color: white;
}

.button-section button:nth-child(2) {
  background-color: #dc3545;
  color: white;
}
</style>